
/**
 * 第四题 myPromise
 * 实现的整体思路：
 * 1、先了解Promise如何使用
 * 2、分析输入和输出的数据
 * 3、分析执行流程
 * 实现的方法：resolve， reject，then（包括异步调用）
 */
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败
class MyPromise {
  constructor (executer) {
    this.status = PENDING
    this.value = null
    this.reason = null
    this.successCallbak = null
    this.failCallback = null
    const resolve = this.resolve.bind(this)
    const reject = this.reject.bind(this)
    executer(resolve, reject)
  }
  // pending的时候不需要执行
  resolve (data) {
    if (this.status !== PENDING) { return false }
    this.value = data
    this.status = FULFILLED
    console.log('res data', data)
    this.successCallbak && this.successCallbak(data)
  }
  reject (reason) {
    if (this.status !== PENDING) { return false }
    this.reason = reason
    this.status = REJECTED
    console.log('rej data', reason)
    this.failCallback && this.failCallback(data)
  }
  // then 接收回调函数，在resolve或者reject的时候执行回调
  then (successCallbak, failCallback) {
    failCallback = failCallback ? failCallback : () => {}
    if (this.status === FULFILLED) {
      successCallbak(this.value)
    } else if (this.status === REJECTED) {
      failCallback(this.reason)
    } else {
      // 处理等待状态和异步情况
      this.successCallbak = successCallbak
      this.failCallback = failCallback
    }
  }
}
module.exports = MyPromise